package com.szholly.pro.watergas_server.ps.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.web.BaseController;
import com.szholly.pro.watergas_server.common.web.RequestUnit;
import com.szholly.data.general.GlobalDataType;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/Task/*")
public class TaskController extends BaseController { 
	protected Logger logger = LoggerFactory.getLogger(getClass());

  /**
   * 获取运维组
   * @param resq
   * @param res
   * @throws Exception
   */
	@RequestMapping(value = "/TaskGenerate")
	public void getOperatorGroupList(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String dateStr = sf.format(new Date());
		
		String sql = " SELECT otc.*,sg.OPERATION_GROUP_ID,ot.FINISH_TIME from OC_TASK_CONFIG otc \n "
				+ "	LEFT JOIN OPERATION_TASK ot ON otc.CURRENT_TASK_CODE = ot.TASK_CODE \n "
				+ " INNER JOIN OPERATION_GROUP_STATION_ASSO sg ON sg.STATION_ID = otc.STATION_ID \n "
				+ "	where otc.CURRENT_TASK_CODE is null or ot.TASK_STATUS = '1' and sg.OPERATION_GROUP_ID is not null ";
		List<RowBase> list = DataUtil.getSelectRows(sql, null);
		List<RowBase> resultList = new ArrayList<>();
		
		for(int i=0;i<list.size();i++){
			
			RowBase row = list.get(i);
			
			if(row.get("CURRENT_TASK_CODE") == null){
				resultList.add(row);
			}
			
			String timeCycle = row.get("TASK_CYCLE")+"";
			Date finishTime = (Date)row.getValue(GlobalDataType.DateTime,"FINISH_TIME");
			
			if(finishTime == null){
				continue;
			}
			
			Calendar deathCal = Calendar.getInstance();
			Calendar currentCal = Calendar.getInstance();
			deathCal.setTime(finishTime);
			int timeCycleNum = Integer.parseInt(timeCycle.replaceAll("[a-zA-Z]",""));
			
			if(timeCycle.indexOf("D")>0){
				deathCal.add(Calendar.DAY_OF_MONTH, timeCycleNum);
			}
			else if(timeCycle.indexOf("M")>0){
				deathCal.add(Calendar.MONTH, timeCycleNum);
			}
			
			if(deathCal.before(currentCal)){
				resultList.add(row);
			}
		}
		
		try {
			
			
			for(int i=0;i<resultList.size();i++){
				RowBase row = resultList.get(i);
				String timeCycle = row.get("TASK_CYCLE")+"";
				String stationId = row.get("STATION_ID")+"";
				String parmId = row.get("PARM_ID")+"";
				String groupId = row.get("OPERATION_GROUP_ID")+"";
				String jobId = row.get("JOB_ID")+"";
				
				DataUtil.beginTransaction();
				
				Object checkExists = DataUtil.getScale(" SELECT COUNT(*) FROM OP_SITE_TASK_COUNT WHERE STATION_ID = '"+stationId+"' ", null);
				
				if((checkExists+"").equals("0")){
					DataUtil.ExecuteUpdateSqlInTransaction("INSERT INTO OP_SITE_TASK_COUNT(STATION_ID,TASK_COUNT,UPDATE_TIME) VALUES('"+stationId+"',1,sysdate)", null);
				}
				else{
					DataUtil.ExecuteUpdateSqlInTransaction(" UPDATE OP_SITE_TASK_COUNT SET TASK_COUNT = TASK_COUNT+1,UPDATE_TIME = sysdate WHERE STATION_ID = '"+stationId+"' ", null);
				}
				
				Object taskCountStr = DataUtil.getScale(" SELECT TASK_COUNT FROM OP_SITE_TASK_COUNT WHERE STATION_ID = '"+stationId+"' ", null);
				
				DataUtil.commitTransaction();
				int taskCount = 0;
				if(taskCountStr != null){
					taskCount = Integer.parseInt(taskCountStr+"");
				}
				
				int timeCycleNum = Integer.parseInt(timeCycle.replaceAll("[a-zA-Z]",""));
				Calendar endCal = Calendar.getInstance();
				if(timeCycle.indexOf("D")>0){
					endCal.add(Calendar.DAY_OF_MONTH, timeCycleNum);
				}
				else if(timeCycle.indexOf("M")>0){
					endCal.add(Calendar.MONTH, timeCycleNum);
				}
				
				String taskCode = dateStr + "-" + stationId + "-" +taskCount;
				String insertSql = " insert into operation_task (GUID,  STATION_ID, PARM_ID, OPERATION_GROUP_ID, TASK_STATUS, START_TIME, END_TIME, FINISH_TIME, FINISH_BY, CREATE_TIME, TASK_CODE, JOB_ID, IS_UNUSUAL) "
						+ "values (sys_guid(), @stationId, @parmId,@groupId, '0', sysdate, @endTime, null, '', sysdate, @taskCode,@jobId, '')";
				
				List<GlobalParameter> parms = new ArrayList<>();
				parms.add(new GlobalParameter("stationId", stationId));
				parms.add(new GlobalParameter("parmId", parmId));
				parms.add(new GlobalParameter("groupId", groupId));
				parms.add(new GlobalParameter("endTime", new java.sql.Date(endCal.getTime().getTime())));
				parms.add(new GlobalParameter("taskCode", taskCode));
				parms.add(new GlobalParameter("jobId", jobId));
				DataUtil.ExecuteUpdateSql(insertSql, parms);
				
				String updateOTCCodeSql = " UPDATE OC_TASK_CONFIG otc SET CURRENT_TASK_CODE = '"+taskCode+"' ";
				DataUtil.ExecuteUpdateSql(updateOTCCodeSql, null);
			}
			
		} catch (Exception e) {
			throw e;
		}
	}
	

	/**
	 * 远程数据异常 生成任务：设备维修，超标比对
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/createTask")
	public void createTask(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String dateStr = sf.format(new Date());
		
		String stationId = RequestUnit.getString("STATION_ID");
		String start_time = RequestUnit.getString("START_TIME");
		String task_type = RequestUnit.getString("TASK_TYPE");
		String groupId = RequestUnit.getString("GROUP_ID");
		
		String overproof_job_id = "2bf6c8b1-12c3-496c-8e1b-96b52157e12c";
		String repaire_job_id = "5ed321b7-99ca-4f0b-b81f-008475d0174a";
		String parmId = "06";
		
		String jobId = repaire_job_id;
		if("1".equals(task_type)){
			jobId = overproof_job_id;
		}
		
		DataUtil.beginTransaction();
		
		Object checkExists = DataUtil.getScale(" SELECT COUNT(*) FROM OP_SITE_TASK_COUNT WHERE STATION_ID = '"+stationId+"' ", null);
		
		if((checkExists+"").equals("0")){
			DataUtil.ExecuteUpdateSql("INSERT INTO OP_SITE_TASK_COUNT(STATION_ID,TASK_COUNT,UPDATE_TIME) VALUES('"+stationId+"',1,sysdate)", null);
		}
		else{
			DataUtil.ExecuteUpdateSql(" UPDATE OP_SITE_TASK_COUNT SET TASK_COUNT = TASK_COUNT+1,UPDATE_TIME = sysdate WHERE STATION_ID = '"+stationId+"' ", null);
		}
		
		Object taskCountStr = DataUtil.getScale(" SELECT TASK_COUNT FROM OP_SITE_TASK_COUNT WHERE STATION_ID = '"+stationId+"' ", null);
		
		DataUtil.commitTransaction();
		
		int taskCount = 0;
		if(taskCountStr != null){
			taskCount = Integer.parseInt(taskCountStr+"");
		}
		
		String taskCode = dateStr + "-" + stationId + "-" +taskCount;
		String insertSql = " insert into operation_task (GUID,  STATION_ID, PARM_ID, OPERATION_GROUP_ID, TASK_STATUS, START_TIME, END_TIME, FINISH_TIME, FINISH_BY, CREATE_TIME, TASK_CODE, JOB_ID, IS_UNUSUAL) "
				+ "values (sys_guid(), @stationId, @parmId,@groupId, '0', @startTime, null, null, '', sysdate, @taskCode,@jobId, '1')";
		
		List<GlobalParameter> parms = new ArrayList<>();
		parms.add(new GlobalParameter("stationId", stationId));
		parms.add(new GlobalParameter("groupId", groupId));
		parms.add(new GlobalParameter("parmId", parmId));
		parms.add(new GlobalParameter("jobId", jobId));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		parms.add(new GlobalParameter("startTime", sdf.parse(start_time)));
		parms.add(new GlobalParameter("taskCode", taskCode));
		
		DataUtil.ExecuteUpdateSql(insertSql, parms);
		
		JSONObject json = new JSONObject();
		json.put("TASK_CODE", taskCode);
		String result = json.toString();
		outString(result);
	}
}
